package com.qwe.graduation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qwe.graduation.utils.exception.Constants;
import com.qwe.graduation.utils.exception.Result;
import com.qwe.graduation.utils.exception.ServiceException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import com.qwe.graduation.service.IVideoService;
import com.qwe.graduation.entity.Video;


/**
 * <p>
 * 视频表 前端控制器
 * </p>
 *
 * @author 林卓锋
 * @since 2023-01-17
 */
@RestController
@RequestMapping("/video")
public class VideoController {

    @Resource
    private IVideoService videoService;

    //新增或更改
    @PostMapping("/save")
    public Result save(@RequestBody Video video) {
        if (video.getId() == null) {
            video.setCreateTime(new Date());
        }
        video.setUpdateTime(new Date());
        if (StringUtils.isBlank(video.getHeadline())) {
            throw new ServiceException(Constants.CODE_400, "视频标题不能为空！");
        }
        if (StringUtils.isBlank(video.getVideoSite())) {
            throw new ServiceException(Constants.CODE_400, "视频地址不能为空！");
        }
        if (StringUtils.isBlank(video.getModule())) {
            throw new ServiceException(Constants.CODE_400, "视频类型不能为空！");
        }

        video.setCreateTime(new Date());
        return Result.success(videoService.saveOrUpdate(video));
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id) {

        return Result.success(videoService.removeById(id));
    }

    //查找全部
    @GetMapping
    public List<Video> findAll() {
        return videoService.list();
    }

    //根据id查询
    @GetMapping("/{id}")
    public List<Video> findOne(@PathVariable String id) {
        return videoService.list();
    }

    //批量删除
    @PostMapping("/delete/batch")
    public Result deleteBeatch(@RequestBody List<String> ids) {
        return Result.success(videoService.removeByIds(ids));
    }

    //分页
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "",required = false) String id,
                           @RequestParam(defaultValue = "",required = false) String module,
                           @RequestParam(defaultValue = "",required = false) String headline) {
        QueryWrapper<Video> queryWrapper =new QueryWrapper<>();
        queryWrapper.orderByDesc("update_time")
                .like("id", id)
                .like("headline",headline)
                .like("module",module);
        Page<Video> page = videoService.page(new Page<>(pageNum, pageSize),queryWrapper);
        return Result.success(page);
    }

}

